package com.yuanqi.Service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanqi.Common.Pojo.Vo.ChatVo;
import com.yuanqi.Common.Pojo.entity.Chat;
import com.yuanqi.Common.config.ThreadLocalConfig;
import com.yuanqi.Common.config.WebSocketConfig;
import com.yuanqi.Mapper.ChatMapper;
import com.yuanqi.Service.ChatService;
import com.yuanqi.WebSocket.MyWebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Objects;

@Service
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements ChatService {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    ThreadLocalConfig threadLocalConfig;

    @Override
    public void bindUser(ChatVo chatVo) {
        String userId = threadLocalConfig.get().get("userId").toString();
        String clientIded = stringRedisTemplate.opsForValue().get(userId+"WebSocket");
        if (clientIded!=null)
        {

            MyWebSocket.map.remove(clientIded);
        }
        if(Objects.equals(chatVo.getType(), "bind"))
        {

          stringRedisTemplate.opsForValue().set(userId+"WebSocket",chatVo.getData().toString());

        }
    }

    @Override
    public void sendMsg(Chat chat) {
        chat.setTime(System.currentTimeMillis()/1000);
        Boolean b = MyWebSocket.sendMsg(chat);
        chat.setIsDelete(0);
        if(b)
        {
            chat.setReaded(0);
            this.save(chat);
        }
        //表示用户没有上线，这个消息等用户上线后传给前端并存储在本地中
        else {
            chat.setReaded(1);
            this.save(chat);
        }
    }


}
